// components/classic/music/index.js
import { classicBeh } from '../classic-bah.js'

const backgroundAudioManager = wx.getBackgroundAudioManager()

Component({
  /**
   * 组件的属性列表
   */
  behaviors: [classicBeh],
  properties: {
    src: String,
    title: String
  },

  /**
   * 组件的初始数据
   */
  data: {
    pauseSrc: "images/player@pause.png",
    playSrc: "images/player@play.png",
    playing: false
  },

  attached(e) {
    this._recoverStatus()
    this._monitorSwitch()
  },

  datached() {
    // mMgr.stop()
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onPlay: function (event) {
      if (!this.data.playing) {
        this.setData({
          playing: true,
        })
        if (backgroundAudioManager.src == this.properties.src) {
          backgroundAudioManager.play()
        }
        else {
          backgroundAudioManager.src = this.properties.src
        }
        backgroundAudioManager.title = '音乐'
      } else {
        this.setData({
          playing: false,
        })
        backgroundAudioManager.pause()
      }
    },

    _recoverStatus() {
      if (backgroundAudioManager.paused) {
        this.setData({
          playing: false
        })
        return
      }
      // bug
      if (backgroundAudioManager.src == this.properties.src) {
        if (!backgroundAudioManager.paused) {
          this.setData({
            playing: true
          })
        }
      }
    },

    _monitorSwitch: function () {
      backgroundAudioManager.onPlay(() => {
        this._recoverStatus()
      })
      backgroundAudioManager.onPause(() => {
        this._recoverStatus()
      })
      backgroundAudioManager.onStop(() => {
        this._recoverStatus()
      }),
        backgroundAudioManager.onEnded(() => {
        this._recoverStatus()
      })
    }
  }
})
